<template>
  <div class="user-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>{{ isEdit ? '编辑用户' : '创建用户' }}</h2>
          <el-button @click="$router.back()">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input
            v-model="form.fullName"
            placeholder="请输入姓名"
          />
        </el-form-item>
        
        <el-form-item label="电话" prop="phoneNumber">
          <el-input
            v-model="form.phoneNumber"
            placeholder="请输入电话号码"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { userApi } from '@/api/userApi'

export default {
  name: 'UserForm',
  components: {
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const formRef = ref()
    const loading = ref(false)
    
    const isEdit = computed(() => route.params.id !== undefined)
    
    const form = reactive({
      username: '',
      password: '',
      email: '',
      fullName: '',
      phoneNumber: ''
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      fullName: [
        { max: 50, message: '姓名长度不能超过 50 个字符', trigger: 'blur' }
      ],
      phoneNumber: [
        { max: 20, message: '电话号码长度不能超过 20 个字符', trigger: 'blur' }
      ]
    }
    
    const loadUser = async (id) => {
      loading.value = true
      try {
        const response = await userApi.getUserById(id)
        if (response.success) {
          const user = response.data
          form.username = user.username
          form.email = user.email
          form.fullName = user.fullName || ''
          form.phoneNumber = user.phoneNumber || ''
        } else {
          ElMessage.error(response.message || '加载用户信息失败')
          router.push('/users')
        }
      } catch (error) {
        console.error('加载用户信息错误:', error)
        ElMessage.error('加载用户信息失败')
        router.push('/users')
      } finally {
        loading.value = false
      }
    }
    
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        loading.value = true
        
        if (isEdit.value) {
          // 更新用户
          const updateData = {
            email: form.email,
            fullName: form.fullName,
            phoneNumber: form.phoneNumber
          }
          
          const response = await userApi.updateUser(route.params.id, updateData)
          if (response.success) {
            ElMessage.success('用户更新成功')
            router.push('/users')
          } else {
            ElMessage.error(response.message || '更新失败')
          }
        } else {
          // 创建用户
          const response = await userApi.createUser(form)
          if (response.success) {
            ElMessage.success('用户创建成功')
            router.push('/users')
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('提交表单错误:', error)
        ElMessage.error('操作失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleReset = () => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    onMounted(() => {
      if (isEdit.value) {
        loadUser(route.params.id)
      }
    })
    
    return {
      formRef,
      form,
      rules,
      loading,
      isEdit,
      handleSubmit,
      handleReset
    }
  }
}
</script>

<style scoped>
.user-form {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 